package Program.AdminUI;

import Program.Information.Complaint;
import Program.Information.User;
import Program.SqlTool.AdminDAO;
import Program.SqlTool.UserDAO;
import Program.Tool.Popup;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Calendar;

public class ComplaintPaneSon extends JPanel {
    //滚动条
    private JScrollPane jScrollPane;
    //表格
    private JTable payedTable;
    //删除按钮
    private JButton deleteJButton;
    //刷新按钮
    private JButton refreshJButton;
    //修改按钮
    private JButton modifyJButton;
    //查看报修详细信息按钮
    private JButton lDetailsJButton;
    //表格模板
    private DefaultTableModel dtm;
    //表题
    private String[] titles = {"投诉单编号", "用户名", "业主姓名", "投诉时间", "处理时间", "投诉详情", "状态"};
    //存储用报修单的集合
    private ArrayList<Complaint> list;
    //存储表格内容
    private Object[][] data;
    //用户类
    private User user;

    public ComplaintPaneSon() {
        super(null);
        setBounds(0, 0, 900, 600);
        setBackground(Color.WHITE);
        list = AdminDAO.getComplaints();
        this.add(initScrollPane());
        initJButton();
    }

    //滚动条面板
    private JScrollPane initScrollPane() {
        jScrollPane = new JScrollPane();
        jScrollPane.setBackground(Color.WHITE);
        jScrollPane.setBounds(0, 0, 900, 500);
        jScrollPane.setViewportView(getViewtable());
        jScrollPane.setOpaque(false);
        jScrollPane.getViewport().setOpaque(false);
        Border js = BorderFactory.createEmptyBorder();
        jScrollPane.setBorder(js);
        return jScrollPane;
    }
    private JTable getViewtable() {
        data = new Object[list.size()][];
        int i = 0;
        for (Complaint complaint : list) {
            data[i++] = setRepairArr(complaint);
        }
        dtm = new DefaultTableModel(data, titles);
        payedTable = new JTable(dtm) {
            // 重写这个表格的方法：设置不可编辑，但可以选中
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        payedTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 16));
        payedTable.setFont(new Font("幼圆", Font.PLAIN, 16));
        payedTable.setRowHeight(30);
        payedTable.getTableHeader().setReorderingAllowed(false);// 设置列不可拖动
        payedTable.getColumnModel().getColumn(5).setPreferredWidth(150);

        // 设置居中
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(JLabel.CENTER);
        payedTable.setDefaultRenderer(Object.class, renderer);
        return payedTable;
    }

    private Object[] setRepairArr(Complaint complaint) {
        user = UserDAO.selectUser(complaint.getUserID());
        //"报修单编号","用户名","业主姓名","报修物品","住址","报修时间","处理时间","报修详情","状态"
        Object[] ComplaintArr = {complaint.getId(), user.getUserName(), user.getName(), complaint.getStartTime(), complaint.getEndTime(), complaint.getDetails(), getState(complaint.getState())};
        return ComplaintArr;
    }

    private void initJButton() {
        deleteJButton = new JButton("删除记录");
        deleteJButton.setBounds(720, 560, 100, 40);
        deleteJButton.setBorder(null);
        deleteJButton.setFocusPainted(false);
        deleteJButton.setBackground(new Color(235, 135, 112));
        deleteJButton.setForeground(Color.WHITE);
        deleteJButton.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        deleteJButton.setToolTipText("Alt+delete可触发按钮");
        deleteJButton.setMnemonic(KeyEvent.VK_DELETE);
        deleteJButton.addActionListener(getListener());

        //刷新按钮
        refreshJButton = new JButton("刷新");
        refreshJButton.setBounds(600, 560, 100, 40);
        refreshJButton.setBorder(null);
        refreshJButton.setFocusPainted(false);
        refreshJButton.setBackground(new Color(191, 230, 240));
        refreshJButton.setForeground(Color.WHITE);
        refreshJButton.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        refreshJButton.setToolTipText("Alt+R可触发按钮");
        refreshJButton.setMnemonic(KeyEvent.VK_R);
        refreshJButton.addActionListener(getListener());

        //按钮
        modifyJButton = new JButton("修改");
        modifyJButton.setBounds(480, 560, 100, 40);
        modifyJButton.setBorder(null);
        modifyJButton.setFocusPainted(false);
        modifyJButton.setBackground(new Color(103, 172, 80));
        modifyJButton.setForeground(Color.WHITE);
        modifyJButton.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        modifyJButton.setToolTipText("Alt+M可触发按钮");
        modifyJButton.setMnemonic(KeyEvent.VK_M);
        modifyJButton.addActionListener(getListener());

        //查看报修详细信息按钮
        lDetailsJButton = new JButton("查看详细信息");
        lDetailsJButton.setBounds(330, 560, 130, 40);
        lDetailsJButton.setBorder(null);
        lDetailsJButton.setFocusPainted(false);
        lDetailsJButton.setBackground(new Color(191, 230, 240));
        lDetailsJButton.setForeground(Color.WHITE);
        lDetailsJButton.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        lDetailsJButton.setToolTipText("Alt+l可触发按钮");
        lDetailsJButton.setMnemonic(KeyEvent.VK_L);
        lDetailsJButton.addActionListener(getListener());

        this.add(deleteJButton);
        this.add(refreshJButton);
        this.add(modifyJButton);
        this.add(lDetailsJButton);
    }

    private ActionListener getListener() {
        ActionListener listener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == deleteJButton) {
                    delRows();
                }else if (e.getSource() == refreshJButton){
                    refreshJPanel();
                }else if (e.getSource() == modifyJButton){
                    modifyRows();
                }else if (e.getSource() == lDetailsJButton){
                    lookDetails();
                }
            }
        };
        return listener;
    }

    //删除选中的行
    private void delRows() {
        ArrayList<Integer> idList = new ArrayList<>();
        int selectRows = payedTable.getSelectedRows().length;
        int[] selectedRows = payedTable.getSelectedRows();
        if (selectRows <= 0) {
            JOptionPane.showMessageDialog(null, "删除前要选中行", "警告", JOptionPane.WARNING_MESSAGE);
        } else {
            // 确认是否删除
            int get = JOptionPane.showOptionDialog(null, "请确认是否删除？", "友情询问", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, new Object[]{"是", "否"}, "否");
            if (get != 1) {
                // 视觉上：倒着删避免数组下标越界
                for (int i = selectRows - 1; i >= 0; i--) {
                    idList.add(Integer.parseInt(dtm.getValueAt(selectedRows[i], 0) + ""));
                    dtm.removeRow(selectedRows[i]);
                    list.remove(i);
                }
                for (Integer integer : idList) {
                    int id = (int) integer;
                    boolean b = UserDAO.delComplaint(id);
                    System.out.println(b);
                }
                refreshJPanel();
            }
        }
    }

    //修改选中的行
    private void modifyRows(){
        ArrayList<Integer> idList = new ArrayList<>();
        int selectRows = payedTable.getSelectedRows().length;
        int[] selectedRows = payedTable.getSelectedRows();
        if (selectRows <= 0) {
            JOptionPane.showMessageDialog(null, "修改前要选中行", "警告", JOptionPane.WARNING_MESSAGE);
        } else {
            // 确认是否修改
            int get = JOptionPane.showOptionDialog(null, "请确认是否修改报修状态？", "友情询问", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, new Object[]{"是", "否"}, "否");
            if (get != 1) {
                // 视觉上：倒着修改避免数组下标越界
                for (int i = selectRows - 1; i >= 0; i--) {
                    idList.add(Integer.parseInt(dtm.getValueAt(selectedRows[i], 0) + ""));
                }
                for (Integer integer : idList) {
                    int id = (int) integer;
                    Complaint complaint = list.get(id - 1);
                    boolean b1 = AdminDAO.modifyCptState(id,complaint.getState());
                    boolean b2 = AdminDAO.modifyCptTime(id, getDateStr(),complaint.getState());
                    System.out.println(b1);
                    System.out.println(b2);
                    if (!b1 || !b2) {
                        String info = "投诉单编号为"+id+"修改失败";
                        Program.Tool.Popup.showJDialog(info);
                    }
                }
                refreshJPanel();
            }
        }
    }

    //查看报修详细信息
    private void lookDetails() {
        int selectRows = payedTable.getSelectedRows().length;
        if (selectRows > 1) {
            JOptionPane.showMessageDialog(null, "请选择指定行", "警告", JOptionPane.WARNING_MESSAGE);
        } else if (selectRows < 1) {
            JOptionPane.showMessageDialog(null, "查看前要选中行", "警告", JOptionPane.WARNING_MESSAGE);
        } else {
            int selectedRow = payedTable.getSelectedRow();
            // 确认是否查看
            int get = JOptionPane.showOptionDialog(null, "请确认是否查看？", "友情询问", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, new Object[]{"是", "否"}, "否");
            if (get != 1) {
                Complaint complaint = list.get(selectedRow);
                String details = complaint.getDetails();
                Popup.showRepairJDialog(details);
            }
        }
    }

    //刷新界面
    private void refreshJPanel(){

        this.removeAll();
        this.repaint();
        this.updateUI();
        UserDAO.updateID("complaint");
        list = AdminDAO.getComplaints();
        this.add(initScrollPane());
        initJButton();
    }


    //获取状态
    private String getState(String state) {
        if (state.equals("0")) {
            return "等待处理";
        } else if (state.equals("1")) {
            return "处理中";
        } else {
            return "完成处理";
        }
    }

    //获取时间
    private String getDateStr() {
        //获取时间对象
        Calendar instance = Calendar.getInstance();
        //3.获取属性
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH) + 1;//Calendar的月份值是0-11
        return year + "/" + month;
    }
}
